<template>
	<view>
		<view class="bgw">
			<view class="flex wrapper">
				<view class="text-gray font-36">
					日期：
				</view>
				<view class="flex-1">
					<picker mode="date" :value="form.day" @change="bindDateChange">
						<view class="blank20"></view>
						<view class="flex">
							<view class="text-right flex-1  font-36 font-bold">
								{{form.day}}
							</view>
							<view class="ml5">
								<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
							</view>
						</view>
						<view class="blank20"></view>
					</picker>
				</view>
			</view>
			<u-line></u-line>
			<view class="flex wrapper">
				<view class="text-gray font-36">
					客户：
				</view>
				<view class="flex-1">
					<picker @change="bindCusChange" :value="cus_index" :range="cus_arr" range-key="label">
						<view class="blank20"></view>
						<view class="flex">
							<view class="text-right flex-1 font-36 font-bold">
								{{cus_arr[cus_index].label || '请选择'}}
							</view>
							<view class="ml5">
								<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
							</view>
						</view>
						<view class="blank20"></view>
					</picker>
				</view>
			</view>
			<u-line></u-line>
			<view class="flex wrapper">
				<view class="text-gray font-36">
					餐别：
				</view>
				<view class="flex-1 flex" style="flex-wrap: wrap;padding: 10upx 0;">
					<view class="mr15" style="margin-top: 10upx;margin-bottom: 10upx;" v-for="(v, i) in dinner_type_arr" :key="i">
						<u-tag :text="v.label" :plain="dinner_type_index != i" type="primary" :name="i" size="large"
							@click="bindDinnerTypeChange(i)"></u-tag>
					</view>
				</view>
			</view>
			<u-line></u-line>
			<view class="flex wrapper">
				<view class="text-gray font-36">
					份数：
				</view>
				<view class="flex-1">
					<view class="blank20"></view>
					<input style="font-size: 36upx;text-align: left;" class="font-bold" v-model="form.qty" type="number"
						placeholder="请输入" />
					<view class="blank20"></view>
				</view>
				<recorder-btn @out="recorderBtnOut"></recorder-btn>
			</view>
		</view>
		<view class="blank20"></view>

		<template v-for="(v,i) in list">
			<view class="bgw wrapper">
				<view class="blank20"></view>
				<view class="flex">
					<view class="flex-1">
						<text class="font-bold font-36">{{v.dish_key_name}}</text>
						<text class="font-bold">【{{v.dish_top_category_name}} | {{v.sales_type == 'kuai'?'快餐':'特色'}}】</text>
					</view>
					<view class="">
						<text class="text-light-gray">差额：</text>
						<text class="font-bold">0</text>
					</view>
				</view>
				<view class="blank20"></view>
				<u-line></u-line>
				<view class="flex">
					<view class="text-gray font-34">
						分餐份数：
					</view>
					<view class="flex-1">
						<view class="blank20"></view>
						<input style="font-size: 36upx;text-align: left;" class="font-bold" v-model="location[i]" type="number"
							placeholder="请输入" />
						<view class="blank20"></view>
					</view>
					<recorder-btn :name="i+''" @out="locationRecorderBtnOut"></recorder-btn>
				</view>
				<u-line></u-line>
				<view class="flex">
					<view class="text-gray font-34">
						实际消耗：
					</view>
					<view class="flex-1">
						<view class="blank20"></view>
						<input style="font-size: 36upx;text-align: left;" class="font-bold" v-model="consumed[i]" type="number"
							placeholder="请输入" />
						<view class="blank20"></view>
					</view>
					<recorder-btn  :name="i+''" @out="consumedRecorderBtnOut"></recorder-btn>
				</view>
				<u-line></u-line>
				<view class="blank20"></view>
				<view class="">
					<u-upload :fileList="fileList[i]" @afterRead="afterRead" @delete="deletePic" :name="i+''" multiple :maxCount="5"></u-upload>
				</view>
			</view>
			<view class="blank20"></view>
		</template>
		<nodata v-if="loadingStatus == 'end' && list.length == 0"></nodata>
		
		<u-gap height="90"></u-gap>
		<cover-view class="fixed-bottom bgw" v-if="list.length != 0">
			<cover-view class="blank20"></cover-view>
			<cover-view class="wrapper">
				<cover-view class="flex">
					<cover-view class="flex-1">
						<cover-view class="reset-btn" @click="resetForm">重置</cover-view>
						<!-- <u-button type="info" class="" text="重置" @click="resetForm"></u-button> -->
					</cover-view>
					<cover-view class="ml15"></cover-view>
					<cover-view class="flex-1">
						<cover-view class="submit-btn" @click="submitForm">确定</cover-view>
						<!-- <u-button type="success" text="确定" @click="submitForm"></u-button> -->
					</cover-view>
				</cover-view>
			</cover-view>
			<cover-view class="blank20"></cover-view>
		</cover-view>
		
	</view>
</template>

<script>
	import recorderBtn from "@/pagesA/components/recorder-btn/recorder-btn.vue";
	import nodata from '@/components/nodata.vue';
	import {
		get_plan_day_distribution_data,
		update_plan_day_distribution_data,
		upload_attachment,
		unlink_attachment
	} from '@/common/api.js';
	export default {
		components: {
			recorderBtn,
			nodata
		},
		data() {
			return {
				loadingStatus:'',
				role: null,
				userInfo: null,
				form: {
					day: '',
					qty: ''
				},
				cus_index: 0,
				dinner_type_index: 0,
				list: [],
				fileList: [],
				location:[],//分餐份数
				consumed:[],//实际消耗
			}
		},
		computed: {
			cus_arr() {
				let write_cus_loc = this.$store.getters.get_role['报表模块']['销售'].write;
				let arr = write_cus_loc.map(v => {
					return {
						label: v[1],
						id: v[0]
					}
				})
				return arr
			},
			dinner_type_arr() {
				let dinner_type_category = this.$store.getters.get_dinner_type_category;
				// console.log(dinner_type_category);
				let arr = dinner_type_category.map(v => {
					return {
						label: v.name,
						id: v.id,
						dinner_type: v.dinner_type
					}
				})
				return arr
			},
		},
		methods: {
			submitForm(){
				let _this = this;
				uni.showLoading({
					title: "加载中",
				});
				let plan_day_distribution_data = this.list.map((v,i)=>{
					let { cus_loc_id,id } = v;
					let item = {
						id,
						cus_loc_id,
						distribution_qty:_this.location[i]||0,
						consumed_qty:_this.consumed[i]||0
					};
					return item;
				})
				update_plan_day_distribution_data({
					plan_day_distribution_data
				}).then((res) => {
					uni.$u.toast('修改成功');
				}).catch((res) => {
				
				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			// 删除图片
			async deletePic(event) {
				console.log(event)
				let filesIndex = Number(event.name);
				let imgIndex = Number(event.index);
				await this.deleteFilePromise(imgIndex,filesIndex);
				this.fileList[filesIndex].splice(imgIndex, 1);
			},
			deleteFilePromise(imgIndex,filesIndex){
				let res_id = this.list[filesIndex].distribution_qty_rec_id;
				let res_model = this.list[filesIndex].distribution_qty_rec_model;
				return unlink_attachment({
					res_model,
					res_id,
					res_field:'img'+(imgIndex+1),
					csrf_token:this.userInfo.csrf_token
				}).then((res)=>{
					console.log(res);
				})
			},
			
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let filesIndex = Number(event.name);
				let id = this.list[filesIndex].id;
				let fileListLen = this.fileList[filesIndex].length;
				lists.map((item) => {
					this.fileList[filesIndex].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url,fileListLen,filesIndex)
					let item = this.fileList[filesIndex][fileListLen]
					this.fileList[filesIndex].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url,imgIndex,filesIndex) {
				let res_id = this.list[filesIndex].distribution_qty_rec_id;
				let res_model = this.list[filesIndex].distribution_qty_rec_model;
				return upload_attachment(url,{
					res_model,
					res_id,
					fname:'img'+(imgIndex+1),
					csrf_token:this.userInfo.csrf_token,
				}).then((res)=>{
					console.log(res);
				})
				// return new Promise((resolve, reject) => {
				// 	// https://fmn315.xyz/web/binary/upload_attachment
				// 	let a = uni.uploadFile({
				// 		url: 'https://fmn315.xyz/gmm/binary/upload_attachment',
				// 		filePath: url,
				// 		name: 'img1',
				// 		formData: {
				// 			model:'gmm.plan_day_distribution_cus_loc_record',
				// 			id:id,
				// 			csrf_token:this.userInfo.csrf_token,
				// 		},
				// 		success: (res) => {
				// 			// console.log(res);
				// 			setTimeout((res) => {
				// 				resolve(res.data.data)
				// 			}, 1000)
				// 		}
				// 	});
				// })
			},
			recorderBtnOut(d) {
				this.form.qty = Number(d);
			},
			consumedRecorderBtnOut(d,name){
				let i = Number(name);
				this.$set(this.consumed,i,Number(d));
			},
			locationRecorderBtnOut(d,name){
				let i = Number(name);
				this.$set(this.location,i,Number(d));
			},
			bindDateChange(e) {
				this.form.day = e.detail.value;
				this.getData();
			},
			bindCusChange(e) {
				let index = e.detail.value;
				this.cus_index = index;
				this.getData();
			},
			bindDinnerTypeChange(index) {
				this.dinner_type_index = index;
				this.getData();
			},
			resetForm() {
				// console.log(this.dinner_type_arr);
				this.form.day = this.today_year_month_day;
				this.form.qty = '';
				this.cus_index = 0;
				let default_dinner_type_index = this.dinner_type_arr.findIndex(v => v.label == '中餐');
				if (default_dinner_type_index == -1) {
					default_dinner_type_index = 0;
				}
				this.dinner_type_index = default_dinner_type_index;
				this.getData();
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				this.loadingStatus = 'loading';
				let day = this.form.day;
				let dinner_type_id = this.dinner_type_arr[this.dinner_type_index].id;
				let cus_loc_id = this.cus_arr[this.cus_index].id;
				let data = {
					day,
					dinner_type_id,
					cus_loc_id
					// day:'2024-03-31',
					// dinner_type_id:110,
					// cus_loc_id:4229
				};
				this.fileList = [];
				this.location = [];
				this.consumed = [];
				get_plan_day_distribution_data(data).then((res) => {
					let list = res.result;
					list.sort((a, b) => a.sequence_tag - b.sequence_tag);
					list.forEach((v,i)=>{
						v.dish_top_category_name = v.dish_top_category_id[1];
						v.dish_key_name = v.dish_key_id[1];
						v.dish_key_id = v.dish_key_id[0];
						v.dish_top_category_id = v.dish_top_category_id[0];
						v.cus_loc_id = cus_loc_id;
						this.fileList.push([]);
						v.img_urls.forEach(url=>{
							// this.fileList[i].push({
							// 	url:'https://cdn.uviewui.com/uview/swiper/1.jpg'
							// })
							if(url){
								this.fileList[i].push({
									url
								})
							}
						});
						
						this.location.push(v.distribution_qty);
						this.consumed.push(v.consumed_qty);
					});
					this.list = list;
				}).catch(() => {

				}).finally(() => {
					this.loadingStatus = 'end';
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			}
		},
		onShow() {
			try {
				console.log(this.$store.getters.get_role);
				this.role = this.$store.getters.get_role;
				this.userInfo = this.$store.getters.get_userInfo;
			} catch (e) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		},
		onLoad(d) {
			// this.list = [{
			// 		name: '雪菜肉丝'
			// 	},
			// 	{
			// 		name: '雪菜肉丝'
			// 	},
			// 	{
			// 		name: '雪菜肉丝'
			// 	},
			// ];
			// this.fileList = [];
			// this.location = [];
			// this.consumed = [];
			// this.list.forEach((v,i)=>{
			// 	this.fileList.push([]);
			// 	this.location.push('');
			// 	this.consumed.push('');
			// });
			this.resetForm();
		}

	}
</script>

<style>
	.fixed-bottom{
		border-top: 1px solid #ebedf0;
		z-index: 9999;
	}
	.reset-btn{
		color: #323233;
		background-color: #fff;
		border-radius: 3px;
		border: 1px solid #ebedf0;
		height: 40px;
		line-height: 40px;
		text-align: center;
	}
	.submit-btn{
		color: #ffffff;
		background-color: #5ac725;
		border-radius: 3px;
		border: 1px solid #5ac725;
		height: 40px;
		line-height: 40px;
		text-align: center;
	}

</style>